// push 消息推送
const uniPushObj = {
	cid: "",
	AppID: "你的AppID",
	AppKey: "你的AppKey",
	AppSecret: "你的AppSecret",
	MasterSecret: "你的MasterSecret",
};

function toJSONStr1(str) {
	//全局将字符串  '{ 和  }' 替换成   {  和   }   ，主要是为了统一"个推推送消息的透传内容的格式（而安卓需要传字符串而导致不是payload不是json对象）  
	str = str.replace(/'{/g, "{").replace(/}'/g, "}");
	str = str.replace(/\"{/g, "{").replace(/}\"/g, "}");
	return str;
}

function toJSONStr2(str) {
	//全局将属性名添加上双引号  "" 
	str = str.replace(/([\$\w]+)\s*:\"/g, function(_, $1) {
		return '"' + $1 + '":"'
	});
	//可能会出现2021-03-13 15:38:42，因此:号后面需加\"加以判断
	str = str.replace(/([\$\w]+)\s*:{/g, function(_, $1) {
		return '"' + $1 + '":{'
	});
	return str;
}

function toJSON(str) { //处理标准格式的字符串成json对象  
	return JSON.parse(str);
}

// 检查app是否开启了通知权限 安卓苹果通用
function checkNotificationAuthorized() {
	const notificationAuthorized = uni.getAppAuthorizeSetting().notificationAuthorized
	if (notificationAuthorized !== 'authorized') {
		uni.showModal({
			title: '通知权限',
			content: '您还没有开启通知权限，无法接受到消息通知，请前往设置！',
			confirmText: '去设置',
			showCancel: false,
			success:(res) => {
				if (res.confirm) uni.openAppAuthorizeSetting()
			}
		});
	}
}

export default {
	// 开启监听推送 
	pushListener() {
		console.log("开启监听推送")
		// 1 判断手机权限 , 如果没有权限就去设置
		//#ifdef APP-PLUS
		checkNotificationAuthorized();
		//#endif
		
		uni.getPushClientId({
			success: (res) => {
				console.log('客户端推送标识:', res)
				uniPushObj.cid = res.cid
				uni.setStorageSync('cid', res.cid);
				uni.onPushMessage(res => {
					console.log("收到推送消息：", res) //监听推送消息
					const {
						type,
						data
					} = res

					if (type == 'click') {
						// 会同时收到两条消息，但payload不一样
						var payload = data.payload;
						console.log('push click payload', payload);
						if (payload.type) {
							console.log('payload.type=' + payload.type)
							let id = payload.id;
							// 流程型
							if (payload.type == 1) {
								let record = {
									myActionId: id
								}

								let pageUrl = '/application/process';
								uni.navigateTo({
									url: `${pageUrl}?record=${JSON.stringify(record)}`,
								});
							} else if (payload.type == 2) {
								let record = {
									id: id
								}

								let pageUrl = '/application/noticeShow';
								uni.navigateTo({
									url: `${pageUrl}?record=${JSON.stringify(record)}`,
								});
							} else if (payload.type == 6) {
								let record = {
									flowId: id
								}

								let pageUrl = '/application/processShow';
								uni.navigateTo({
									url: `${pageUrl}?record=${JSON.stringify(record)}`,
								});
							} else {
								// oa_message
								let record = {
									id: id
								}
								url: `/application/news/newsShowPage?record=${JSON.stringify(record)}`
							}
						}
					} else if (type == 'receive') {
						var payload = data.payload;
						if (typeof(payload) == "string") {
							payload = payload.replace(/{dept}/g, '');
							// 正常格式：{title:"请注意查看待办流程：@admin   234243324",content:"管理员请您及时处理：@admin   234243324等级：普通发起人：管理员发起时间：2021-03-13 15:38:42",payload:"{"realName":"管理员","id":"103","type":"1","title":"@admin   234243324","flowName":"@admin   234243324","flowType":"1"}"}
							payload = toJSON(toJSONStr2(toJSONStr1(payload)));
						}

						console.log('payload', payload);
						var messageTitle = payload.title;
						var messageContent = payload.content;
						uni.createPushMessage({
							title: messageTitle,
							content: messageContent,
							payload: JSON.stringify(payload.payload)
						})
					}
				})
			},
			fail(err) {
				console.log("getPushClientId-err", err)
			}
		})

	},
}